package com.ccrego.haiyi.utils;

import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Description:
 * Created by Andy Hong on 10/17/2017.
 */

public class ImageFileManager {
    private static final String POSTFIX = ".jpg";
    private static final String IMAGE_PATH = "/ccregohaiyi/image/";
    private static final String AUTHORITIES = "com.ccrego.haiyi.provider";

    public static Uri createMediaUri(Context context, File imageFile) {
        Uri uri;
        if (Build.VERSION.SDK_INT > 23) {
            uri = FileProvider.getUriForFile(context, AUTHORITIES, imageFile);
        } else {
            uri = Uri.fromFile(imageFile);
        }

        return uri;
    }

    public static File createImageFile(Context context) {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date());

        File rootFile = getImageRootDir(context);
        if (!rootFile.exists()) {
            rootFile.mkdirs();
        }
        return new File(rootFile, "IMAGE" + "_" + timeStamp + POSTFIX);

    }

    public static File cropImageFile(Context context) {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date());

        File rootFile = getImageRootDir(context);
        if (!rootFile.exists()) {
            rootFile.mkdirs();
        }
        return new File(rootFile, "IMAGE" + "_" + timeStamp + "crop" + POSTFIX);
    }

    private static File getImageRootDir(Context context) {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state) ?
                new File(Environment.getExternalStorageDirectory() + IMAGE_PATH) :
                new File(context.getCacheDir() + IMAGE_PATH);
    }
}
